<template>
  <!-- 系统功能-文件管理 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :model="filterForm" :inline="true">
          <el-form-item label="文件名称" prop="fileOriginName">
            <el-input v-model.trim="filterForm.fileOriginName" maxlength="100" clearable
                      placeholder="请输入内容" class="filter-item limit" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item label="存储位置" prop="fileLocation">
            <el-select
              v-model="filterForm.fileLocation"
              placeholder="请选择存储位置"
              class="filter-item"
            >
              <el-option
                v-for="item in addressList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <el-button
          class="filter-item"
          type="primary"
          @click="handleFilter"
        >
          搜索
        </el-button>
        <el-button @click="handleReset"> 重置</el-button>
      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['SYS_FILE_ADD_BUTTON']"
            class="filter-item"
            icon="el-icon-upload2"
            type="primary"
            @click="fileUploadVisible=true"
          >
            点击上传
          </el-button>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="listLoading"
          :data="fileList"
          highlight-current-row
          style="width: 100%;"
          :header-cell-style="headerCellStyle"
          border
          @sort-change="sortChange"
        >
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            :index="table_index"
          />
          <el-table-column
            v-if="columns[0].show"
            key="fileObjectName"
            align="center"
            prop="fileObjectName"
            min-width="130"
            label="文件/图片"
          >
            <template slot-scope="{row}">
              <el-image
                v-if="row.fileSuffix === 'png' || row.fileSuffix === 'jpg'||row.fileSuffix === 'jpeg'"
                style="height: 40px;"
                :preview-src-list="imageSrcList"
                :src=" row.imgUrl ||baseURL() + '/sysFileInfo/previewByObjectName?fileBucket=' +
                  row.fileBucket + '&fileObjectName=' + row.fileObjectName"
                fit="contain"
              />
              <div v-else> {{ row.fileSuffix }} 文件</div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns[1].show"
            key="fileLocation"
            align="center"
            prop="fileLocation"
            min-width="110"
            label="存储位置"
          >
            <template slot-scope="{row}">
              <div v-for="item in addressList" :key="item.id">
                <p v-if="item.value === row.fileLocation">
                  {{ item.name }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns[2].show"
            key="fileOriginName"
            align="center"
            min-width="110"
            prop="fileOriginName"
            label="文件名称"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column
            v-if="columns[3].show"
            key="secretFlag"
            align="center"
            prop="secretFlag"
            width="110"
            label="是否机密"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.secretFlag === 'N'?'否':'是' }}</p>
            </template>
          </el-table-column> -->
          <el-table-column
            v-if="columns[3].show"
            key="fileSuffix"
            align="center"
            width="120"
            prop="fileSuffix"
            label="文件后缀"
          />
          <el-table-column
            v-if="columns[4].show"
            key="fileSizeInfo"
            align="center"
            prop="fileSizeInfo"
            width="120"
            label="文件大小"
          />
          <el-table-column
            v-if="columns[5].show"
            key="createTime"
            align="center"
            prop="createTime"
            label="创建时间"
            min-width="120"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[6].show"
            key="createUserName"
            align="center"
            width="120"
            prop="createUserName"
            label="创建人"
          />
          <el-table-column
            :key="Math.random()"
            label="操作"
            align="center"
            width="204px"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template slot-scope="{ row }">
              <el-button
                v-permission="['SYS_FILE_DOWNLOAD_BUTTON']"
                size="mini"
                style="padding: 7px"
                @click="downloadImage(row)"
              >
                下载
              </el-button>
              <el-button
                v-permission="['SYS_FILE_DETAIL_BUTTON']"
                size="mini"
                style="padding: 7px"
                @click="fileInfoDetails(row)"
              >
                详情
              </el-button>
              <el-button
                v-permission="['SYS_FILE_DEL_BUTTON']"
                type="danger"
                size="mini"
                style="padding: 7px"
                title="确定删除吗？"
                :disabled="row.fileObjectName =='用户信息导入模板.xls'"
                @click="deleteImage(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="filterForm.pageNo"
          :limit.sync="filterForm.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 文件上传 -->
      <dtDialog
        title="文件上传"
        :visible.sync="fileUploadVisible"
        :footer-slot="true"
        width="620px"
      >
        <el-form slot="content">
          <el-upload
            ref="fileUploadRef"
            class="upload-demo filter-item"
            drag
            :action="baseURL() +'/sysFileInfo/upload?secretFlag=N'"
            :headers="uplaodHeaders"
            :before-upload="beforeHandleSuccess"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :on-progress="onProgress"
            :show-file-list="true"
            :multiple="false"
            :limit="1"
            :on-exceed="onExceed"
          >
            <i class="el-icon-upload" />
            <div v-loading.fullscreen.lock="uploadLoading" class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">最大可上传10M的文件</div>
          </el-upload>
        </el-form>
      </dtDialog>
      <!-- 详情弹窗 -->
      <dtDialog
        title="详情"
        :visible.sync="fileVisible"
        :footer-slot="true"
        @close="resetTemp"
      >
        <el-form
          ref="fileDataForm"
          slot="content"
          :rules="fileRules"
          :model="fileTemp"
          label-position="right"
          label-width="72px"
        >
          <el-form-item v-if="fileTemp.fileSuffix === 'png' || fileTemp.fileSuffix === 'jpg'||fileTemp.fileSuffix === 'jpeg'" label="图片">
            <el-image
              v-if="fileTemp.fileSuffix === 'png' || fileTemp.fileSuffix === 'jpg'||fileTemp.fileSuffix === 'jpeg'"
              style="height: 80px;"
              :preview-src-list="imageSrcList"
              :src=" fileTemp.imgUrl ||baseURL() + '/sysFileInfo/previewByObjectName?fileBucket=' +
                fileTemp.fileBucket + '&fileObjectName=' + fileTemp.fileObjectName"
              fit="contain"
            />
            <div v-else> {{ fileTemp.fileSuffix }} 文件</div>
          </el-form-item>
          <el-form-item label="存储位置" prop="fileLocation">
            <el-select
              v-model="fileTemp.fileLocation"
              style="width: 100%"
              class="filter-item"
              disabled
            >
              <el-option
                v-for="item in addressList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文件仓库" prop="fileBucket">
            <el-input v-model="fileTemp.fileBucket" readonly disabled />
          </el-form-item>
          <el-form-item label="文件名称" prop="fileOriginName">
            <el-input v-model="fileTemp.fileOriginName" readonly disabled />
          </el-form-item>
          <!-- <el-form-item label="机密文件" prop="secretFlag">
            <el-input v-model="fileTemp.secretFlag" readonly disabled />
          </el-form-item> -->
          <el-form-item label="文件后缀" prop="fileSuffix">
            <el-input v-model="fileTemp.fileSuffix" readonly disabled />
          </el-form-item>
          <el-form-item label="文件大小" prop="fileSizeInfo">
            <el-input v-model="fileTemp.fileSizeInfo" readonly disabled />
          </el-form-item>
        </el-form>
      </dtDialog>
    </div>
  </div>
</template>
<script>
import sysFileInfo from '@/framework/api/sysFileInfo'
import { getToken } from '@/framework/utils/auth'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'
import { cloud } from '@/framework/utils/request'

export default {
  name: 'SysFile',
  mixins: [dialogColumn],
  data() {
    return {
      filterForm: {
        pageNo: 1,
        pageSize: 10,
        fileLocation: '',
        fileOriginName: ''
      },
      total: 0,
      addressList: [
        { id: 2, name: '本地', value: 4 },
        { id: 3, name: '阿里云', value: 1 },
        { id: 4, name: '腾讯云', value: 2 },
        { id: 5, name: 'minio', value: 3 }
      ],
      listLoading: true,
      fileList: [],
      imageSrcList: [],
      fileVisible: false,
      fileUploadVisible: false,
      fileTemp: {},
      fileRules: {},
      uploadLoading: false,
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      uplaodHeaders: {
        Authorization: getToken()
      },
      fileListLength: 0,
      // 列信息
      columns: [
        { prop: 'fileObjectName', label: '文件/图片', show: true },
        { prop: 'fileLocation', label: '存储位置', show: true },
        { prop: 'fileOriginName', label: '文件名称', show: true },
        // { prop: 'secretFlag', label: `是否机密`, show: true },
        { prop: 'fileSuffix', label: '文件后缀', show: true },
        { prop: 'fileSizeInfo', label: '文件大小', show: true },
        { prop: 'createTime', label: '创建时间', show: true },
        { prop: 'createUserName', label: '创建人', show: true }
      ]
    }
  },
  watch: {
    fileUploadVisible: {
      handler(n, o) {
        if (!n) {
          this.$nextTick(() => {
            this.$refs.fileUploadRef.clearFiles()
          })
        }
      }
    }
  },
  created() {
    this.handleFilter()
  },
  methods: {
    handleReset() {
      this.$refs.filterFormRef.resetFields()
      this.handleFilter()
    },
    baseURL() {
      return process.env.VUE_APP_BASE_API + cloud.file
    },
    sortChange(data) {
    },
    handleFilter() {
      this.filterForm.pageNo = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      sysFileInfo.fileInfoListPage(this.filterForm).then((res) => {
        this.fileList = res.data.rows
        this.total = res.data.totalRows
        this.fileListLength = res.data.rows.length
        this.listLoading = false
        this.fileList.map((row) =>
          this.imageSrcList.push(row.imgUrl || `${this.baseURL()}/sysFileInfo/previewByObjectName?fileBucket=${
            row.fileBucket}&fileObjectName=${row.fileObjectName}`))
      })
    },
    onExceed(files, fileList) {
      this.dtMessage.error('单次只能上传一个文件!')
    },
    onProgress(event, file, fileList) {
      this.uploadLoading = true
    },
    uploadSuccess(response, file, fileList) {
      this.uploadLoading = false
      this.$dtMessage({
        title: '成功',
        message: '上传成功',
        type: 'success',
        duration: 2000
      })
      this.fileUploadVisible = false
      this.getList()
    },
    uploadError(err, file, fileList) {
      this.uploadLoading = false
      this.$message.error(err)
    },
    beforeHandleSuccess(file) {
      const isLt10M = file.size / 1024 / 1024 <= 10
      if (!isLt10M) {
        this.$message.error('您上传文件超过系统限制的最大值，最大可上传10M的文件!')
        return false
      }
      if (file.name.length > 50) {
        this.$message.error('文件名称过长，建议长度在50字符内!')
        return false
      }
      return true
    },
    downloadImage(row) {
      let url = this.baseURL()
      const hasToken = getToken()
      if (row.secretFlag === 'Y') {
        url += `/sysFileInfo/privateDownload?fileId=${row.fileId}&token=${hasToken}`
      } else {
        url += `/sysFileInfo/publicDownload?fileId=${row.fileId}&token=${hasToken}`
      }
      window.location.href = url
    },
    fileInfoDetails(row) {
      sysFileInfo.detail(row.fileId).then((res) => {
        this.fileTemp = res.data
        this.fileVisible = true
      })
    },
    resetTemp() {
      this.fileTemp = {}
    },
    deleteImage(row) {
      this.$dtMessageBox({ title: '提示', message: '确认删除该条数据吗？', type: 'warning' }).then(() => {
        sysFileInfo.deleteReally(row).then((res) => {
          this.getList()
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    table_index(index) {
      return (this.filterForm.pageNo - 1) * this.filterForm.pageSize + index + 1
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-upload{
  width: 100%;
  .el-upload-dragger{
    width: 100%;
  }
}
</style>
